package com.taoism.utils;

import org.apache.tomcat.util.codec.binary.Base64;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class Base64ToPhotoUtils {
    /**
     * 通过BASE64Decoder解码,并生成图片
     *
     * @param imgStr 解码后的string
     * @throws IOException
     */
    public static String string2Image(String imgStr, String imgFilePath) {
        String paths = "/" + new SimpleDateFormat("yyyy").format(new Date()) + "/"
                + new SimpleDateFormat("MM").format(new Date()) + "/" + new SimpleDateFormat("dd").format(new Date());
        String filePath = imgFilePath + paths;
        // 对字节数组字符串进行Base64解码并生成图片
        File f = new File(filePath);
        if (!f.exists()) {
            f.mkdirs();
        }
        String uuid = UUID.randomUUID().toString();
        filePath = filePath + "/" + uuid + ".jpg";
        //paths="/upload"+paths+"/"+ uuid + ".jpg";
        byte[] bytes = Base64.decodeBase64(imgStr.getBytes());
        byte[] buffer = new byte[1024];
        try (FileOutputStream out = new FileOutputStream(filePath);
             ByteArrayInputStream in = new ByteArrayInputStream(bytes)) {
            int byteread = 0;
            while ((byteread = in.read(buffer)) != -1) {
                out.write(buffer, 0, byteread); // 文件写操作
                out.flush();
            }
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return filePath;
    }


}
